varying vec3 vertexNormal;
varying vec3 position;

void main()
{
	// normalize the vertex normal and the view vector
	vec3 normal = normalize(vertexNormal);
	vec3 view = normalize(-position);

	// these variables will accumulate for each light
	vec4 ambient = gl_FrontLightModelProduct.sceneColor;
	vec4 diffuse = vec4(0,0,0,0);
	vec4 specular = vec4(0,0,0,0);

	// accumulate ambient, diffuse, and specular for each light
	for (int i = 0; i < gl_MaxLights; i++)
	{
		// early out if the current light is disabled
		if (gl_LightSource[i].diffuse[3] == 0)
			continue;

		// determine the light and light reflection vectors
		vec3 light =
			normalize(gl_LightSource[i].position.xyz - position);
		vec3 reflected = -reflect(light, normal); 

		// add the current light's ambient value
		ambient += gl_FrontLightProduct[i].ambient;

		// calculate and add the current light's diffuse value
		float calculatedDiffuse = max(dot(normal, light), 0.0);
		diffuse += gl_FrontLightProduct[i].diffuse *
			calculatedDiffuse;

		// calculate and add the current light's specular value
		float calculatedSpecular = pow(max(dot(reflected, view), 0.0),
			0.3 * gl_FrontMaterial.shininess);
		specular += clamp(gl_FrontLightProduct[i].specular *
			calculatedSpecular, 0.0, 1.0);
	}

	gl_FragColor = ambient + diffuse + specular;
}
